package com.hand.wfive.loginAndVip.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import com.hand.wfive.App
import com.hand.wfive.BuildConfig
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.ad.AdConfig
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.loginAndVip.*
import com.hand.wfive.loginAndVip.alipay.AliPay
import com.hand.wfive.loginAndVip.alipay.OrderInfoUtil
import com.hand.wfive.loginAndVip.model.*
import com.hand.wfive.loginAndVip.wechatpay.WechatModel
import com.hand.wfive.loginAndVip.wechatpay.WechatPay
import com.hand.wfive.loginAndVip.wechatpay.WechatPayTools
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import com.qmuiteam.qmui.widget.dialog.QMUIDialog.MessageDialogBuilder
import com.rxjava.rxlife.RxLife
import kotlinx.android.synthetic.main.login_activity_vip.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.toast
import rxhttp.wrapper.param.RxHttp

@Deprecated("已废弃，旧版vip")
class VipActivity : BaseActivity() {

    private lateinit var curVipType: String
    private val vipList = ArrayList<VipGoodsModel>()
    private var retryCount = 3
    private var isWechatPay = true
    private var isWechatAppPay = 0
    private var isAliAppPay = 0

    private lateinit var mTurnH5Pay: ActivityResultLauncher<Intent>

    override fun getContentViewId() = R.layout.login_activity_vip

    override fun init() {
        registerEventBus()

        topBar.updateBottomSeparatorColor(Color.TRANSPARENT)
        val backBtn = topBar.addLeftImageButton(R.mipmap.login_back, R.id.top_bar_left_image)
        backBtn.singleClick { finish() }

        curVipType = VipGoodsModel.FOREVER_VIP
        vipLayout1.isSelected = true
        originalPrice1.paintFlags = originalPrice1.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        originalPrice2.paintFlags = originalPrice2.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        originalPrice3.paintFlags = originalPrice3.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG

        mTurnH5Pay = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == RESULT_OK) {
                showLoadingC()
                UserManager.getInstance().initUser()
            }
        }

        getVipPriceConfig()
    }

    private fun getVipPriceConfig() {
        showLoading("请稍后...")
        RxHttp.postForm(ApiConfig.queryVipPriceByKey)
            .add("key", LoginConfig.AppId)
            .asClass(VipConfigModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({ apiModel ->
                if (apiModel.code == ApiConfig.SUCCESSCODE) {
                    isWechatAppPay = apiModel.isWechatAppPay
                    isAliAppPay = apiModel.isAliAppPay
                    if (isWechatAppPay == 1 && LoginConfig.WeChatAppId.isEmpty()) {
                        // 开启微信支付并且未接微信支付时：隐藏微信支付选项
                        payWechat.isVisible = false
                    }
                    if (isAliAppPay == 1 && AliPayConfig.APPID.isEmpty()) {
                        // 开启支付宝支付并且未接支付宝支付时：隐藏支付宝支付选项
                        payAli.isVisible = false
                    }
                    if (!payWechat.isVisible) {
                        // 微信支付选项隐藏
                        if (payAli.isVisible) {
                            // 支付宝选项显示
                            isWechatPay = false
                            payWechat.setImageResource(R.mipmap.login_vip_wechat_pay_nor)
                            payAli.setImageResource(R.mipmap.login_vip_ali_pay_sel)
                        } else {
                            // 支付宝选项隐藏时
                            showNoPayWayDialog()
                        }
                    }

                    val tmpList = apiModel.obj
                    if (tmpList.isNotEmpty()) {
                        vipList.addAll(tmpList)
                        if (vipList.size == 3) {
                            updateVipInfo()
                        } else {
                            showRetryDialog()
                        }
                    } else {
                        showRetryDialog()
                    }
                    hideLoading()
                } else {
                    showRetryDialog()
                    hideLoading()
                }
            }, {
                hideLoading()
                showRetryDialog()
            })
    }

    @SuppressLint("SetTextI18n")
    private fun updateVipInfo() {
        for (i in vipList.indices) {
            val model = vipList[i]
            when (model.productName) {
                VipGoodsModel.FOREVER_VIP -> {
                    name1.text = model.productName
                    price1.text = "¥${model.productPrice}"
                    originalPrice1.text = "¥${model.productOriginalPrice}"
                }

                VipGoodsModel.YEAR_VIP -> {
                    name2.text = model.productName
                    price2.text = "¥${model.productPrice}"
                    originalPrice2.text = "¥${model.productOriginalPrice}"
                }

                VipGoodsModel.MONTH_VIP -> {
                    name3.text = model.productName
                    price3.text = "¥" + model.productPrice
                    originalPrice3.text = "¥" + model.productOriginalPrice
                }
            }
        }
        when (curVipType) {
            VipGoodsModel.FOREVER_VIP -> {
                openVip.text = "${price1.text}  开通VIP"
            }

            VipGoodsModel.YEAR_VIP -> {
                openVip.text = "${price2.text}  开通VIP"
            }

            VipGoodsModel.MONTH_VIP -> {
                openVip.text = "${price3.text}  开通VIP"
            }
        }
    }

    private fun showNoPayWayDialog() {
        MessageDialogBuilder(this).setTitle("提示").setMessage("支付渠道获取失败")
            .setCancelable(false).setCanceledOnTouchOutside(false)
            .addAction("退出") { dialog, _ ->
                dialog.dismiss()
                finish()
            }.show()
    }

    private fun showRetryDialog() {
        MessageDialogBuilder(this).setTitle("提示").setMessage("会员数据加载失败")
            .setCancelable(false).setCanceledOnTouchOutside(false)
            .addAction("退出") { dialog, _ ->
                dialog.dismiss()
                finish()
            }.addAction("重试") { dialog, _ ->
                dialog.dismiss()
                getVipPriceConfig()
            }.show()
    }

    @SuppressLint("SetTextI18n")
    fun vipBtnClick(view: View) {
        if (NoFastClickUtils.isFastClick()) return
        when (view) {
            payWechat -> {
                isWechatPay = true
                payWechat.setImageResource(R.mipmap.login_vip_wechat_pay_sel)
                payAli.setImageResource(R.mipmap.login_vip_ali_pay_nor)
            }

            payAli -> {
                isWechatPay = false
                payWechat.setImageResource(R.mipmap.login_vip_wechat_pay_nor)
                payAli.setImageResource(R.mipmap.login_vip_ali_pay_sel)
            }

            vipLayout1 -> {
                curVipType = VipGoodsModel.FOREVER_VIP
                openVip.text = "${price1.text}  开通VIP"
                vipLayout1.isSelected = true
                vipLayout2.isSelected = false
                vipLayout3.isSelected = false
                vipLayout1.setBackgroundResource(R.mipmap.login_vip_price_check1)
                vipLayout2.setBackgroundResource(R.mipmap.login_vip_price_normal)
                vipLayout3.setBackgroundResource(R.mipmap.login_vip_price_normal)
            }

            vipLayout2 -> {
                curVipType = VipGoodsModel.YEAR_VIP
                openVip.text = "${price2.text}  开通VIP"
                vipLayout1.isSelected = false
                vipLayout2.isSelected = true
                vipLayout3.isSelected = false
                vipLayout1.setBackgroundResource(R.mipmap.login_vip_price_normal1)
                vipLayout2.setBackgroundResource(R.mipmap.login_vip_price_check)
                vipLayout3.setBackgroundResource(R.mipmap.login_vip_price_normal)
            }

            vipLayout3 -> {
                curVipType = VipGoodsModel.MONTH_VIP
                openVip.text = "${price3.text}  开通VIP"
                vipLayout1.isSelected = false
                vipLayout2.isSelected = false
                vipLayout3.isSelected = true
                vipLayout1.setBackgroundResource(R.mipmap.login_vip_price_normal1)
                vipLayout2.setBackgroundResource(R.mipmap.login_vip_price_normal)
                vipLayout3.setBackgroundResource(R.mipmap.login_vip_price_check)
            }

            openVip -> {
                if (UserManager.getInstance().isVip) {
                    showNormalTip(topBar, "您已经是会员了")
                    return
                }
                val price = getSelectPrice()
                if (price.isNullOrEmpty()) {
                    showErrorTip(topBar, "会员数据加载失败")
                } else {
                    if (isWechatPay) {
                        if (isWechatAppPay == 1) {
                            startWechatPay(price.toInt() * 100)
                        } else {
                            startWechatH5Pay(price)
                        }
                    } else {
                        if (isAliAppPay == 1) {
                            startAliPay(price.toInt())
                        } else {
                            startWechatH5Pay(price, "alipay")
                        }
                    }
                }
            }

            buyNow -> PrivacyActivity.showRule(this, PrivacyActivity.VIPRULE)
        }
    }

    private fun getSelectPrice(): String? {
        for (i in vipList.indices) {
            val model = vipList[i]
            if (curVipType == model.productName) {
                return model.productPrice
            }
        }
        return "0"
    }

    /**
     * 开始微信支付
     */
    private fun startWechatPay(price: Int) {
        var iPrice = price
        val outTradeNo = getOutTradeNo()
        if (TextUtils.isEmpty(outTradeNo)) {
            toast("请重新登录")
            finish()
            return
        }
        if (BuildConfig.DEBUG) {
            iPrice = 1
        }
        var payModel: WechatModel? = null
        when (curVipType) {
            VipGoodsModel.FOREVER_VIP -> {
                payModel = WechatModel(
                    outTradeNo, iPrice.toString(),
                    "${name1.text}-${getString(R.string.app_name)}",
                    packageName, LoginConfig.WeChatPayCallbackUrl
                )
            }

            VipGoodsModel.YEAR_VIP -> {
                payModel = WechatModel(
                    outTradeNo, iPrice.toString(),
                    "${name2.text}-${getString(R.string.app_name)}",
                    packageName, LoginConfig.WeChatPayCallbackUrl
                )
            }

            VipGoodsModel.MONTH_VIP -> {
                payModel = WechatModel(
                    outTradeNo, iPrice.toString(),
                    "${name3.text}-${getString(R.string.app_name)}",
                    packageName, LoginConfig.WeChatPayCallbackUrl
                )
            }
        }
        if (payModel == null) {
            toast("会员信息获取失败")
            finish()
            return
        }
        showLoading("正在支付，请稍后...")
        retryCount = 3
        WechatPayTools.wechatPayUnifyOrder(
            this, LoginConfig.WeChatAppId, LoginConfig.WeChatMch_id,
            LoginConfig.WeChatPrivateKey, payModel
        ) { code, msg ->
            runOnUiThread {
                if (code == WechatPay.SUCCESS_PAY) {
                    openVip(outTradeNo)
                } else {
                    hideLoading()
                    showErrorTip(topBar, msg)
                }
            }
        }
    }

    private fun startWechatH5Pay(price: String, type: String = "wxpay") {
        /*
         http://www.quexingnet.cn/m/orderApi/view?
         code=2666236898829_1979_huawei
         &amount=0.01
         &name=学拼音发音点读
         &remark=永久会员-学拼音发音点读
         &appid=627b114030a4f67780d3e779
         &vipType=0
         &username=test1234
         &userid=1111
         &type=alipay or wxpay
         */
        val payPrice = price
        val name = getString(R.string.app_name)
        val remark = when (curVipType) {
            VipGoodsModel.FOREVER_VIP -> "${name1.text}-${name}"
            VipGoodsModel.YEAR_VIP -> "${name2.text}-${name}"
            else -> "${name3.text}-${name}"
        }
        val user = UserManager.getInstance().curUser
        val orderUrl = "${ApiConfig.basePayUrl}orderApi/view?" +
                "code=${getOutTradeNo()}&amount=${payPrice}&name=${remark}" +
                "&remark=${remark}&appid=${LoginConfig.AppId}" +
                "&vipType=${VipConfig.getVipValueByText(curVipType)}" +
                "&username=${user.username}&userid=${user.id}&type=${type}"
        mTurnH5Pay.launch(H5PayActivity.showIntent(mContext, orderUrl, type))
    }

    /**
     * 开始支付宝支付
     */
    private fun startAliPay(price: Int) {
        val outTradeNo = getOutTradeNo()
        if (TextUtils.isEmpty(outTradeNo)) {
            finish()
            Toast.makeText(this, "请重新登录", Toast.LENGTH_SHORT).show()
            return
        }
        var body = getString(R.string.app_name)
        when (curVipType) {
            VipGoodsModel.FOREVER_VIP -> {
                body = body + "-" + name1.text.toString()
            }

            VipGoodsModel.YEAR_VIP -> {
                body = body + "-" + name2.text.toString()
            }

            VipGoodsModel.MONTH_VIP -> {
                body = body + "-" + name3.text.toString()
            }
        }
        var priceValue = price.toString()
        /*if (BuildConfig.DEBUG) {
            priceValue = "0.01"
        }*/
        val params = OrderInfoUtil.buildOrderParamMap(
            AliPayConfig.APPID, true, App.getContext().packageName, priceValue, body, outTradeNo
        )
        val orderParam = OrderInfoUtil.buildOrderParam(params)
        val sign = OrderInfoUtil.getSign(params, AliPayConfig.RSA2_PRIVATE, true)
        val orderInfo = "$orderParam&$sign"
        showLoading("正在支付，请稍后...")
        val builder = AliPay.Builder(this)
        builder.orderInfo(orderInfo)
        /*
         * 参数解释
         *
         * @param status 是结果码(类型为字符串)。
         * 9000	订单支付成功
         * 8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
         * 4000	订单支付失败
         * 5000	重复请求
         * 6001	用户中途取消
         * 6002	网络连接出错
         * 6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
         * 其它	其它支付错误
         * @param json        是处理结果(类型为json结构字符串)
         * out_trade_no	String	是	64	商户网站唯一订单号	70501111111S001111119
         * trade_no	String	是	64	该交易在支付宝系统中的交易流水号。最长64位。	2014112400001000340011111118
         * app_id	String	是	32	支付宝分配给开发者的应用Id。	2014072300007148
         * total_amount	Price	是	9	该笔订单的资金总额，单位为RMB-Yuan。取值范围为[0.01,100000000.00]，精确到小数点后两位。	9.00
         * seller_id	String	是	16	收款支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字	2088111111116894
         * msg	String	是	16	处理结果的描述，信息来自于code返回结果的描述	success
         * charset	String	是	16	编码格式	utf-8
         * timestamp	String	是	32	时间	2016-10-11 17:43:36
         * code	String	是	16	结果码	具体见
         * @param description description是描述信息(类型为字符串)
         */
        builder.listener { status, _, _ ->
            when (status) {
                "9000" -> { //成功
                    openVip(outTradeNo)
                }

                "6001" -> { //用户取消
                    hideLoading()
                    showNormalTip(topBar, "支付取消")
                }

                else -> { //支付失败
                    hideLoading()
                    showErrorTip(topBar, "支付失败")
                }
            }
        }
        builder.loading(true)
        builder.build()
    }

    /**
     * 生成订单号
     */
    private fun getOutTradeNo(): String {
        val randomInt = ((Math.random() * 9 + 1) * 1000).toInt()
        return "${System.currentTimeMillis()}_${randomInt}_${getString(R.string.channel)}"
    }

    /**
     * 支付成功需要将vip信息存到服务器
     */
    private fun openVip(out_trade_no: String) {
        RxHttp.postForm(ApiConfig.modifyVip)
            .add("appid", LoginConfig.AppId)
            .add("username", UserManager.getInstance().curUser.username)
            .add("psw", UserManager.getInstance().curUser.password)
            .add("vipType", VipConfig.getVipValueByText(curVipType))
            .add("orderNo", out_trade_no)
            .asClass(ApiModel::class.java)
            .to(RxLife.toMain(this))
            .subscribe({ apiModel ->
                hideLoading()
                if (apiModel.code == ApiConfig.SUCCESSCODE) {
                    val user = apiModel.obj
                    user.password = UserManager.getInstance().curUser.password
                    successOpenVip(user)
                } else {
                    if (retryCount > 0) {
                        retryCount--
                        topBar.postDelayed({ openVip(out_trade_no) }, 1000)
                    } else {
                        hideLoading()
                        val user = UserManager.getInstance().curUser
                        user.isVip = 1
                        user.vipType = VipConfig.getVipValueByText(curVipType)
                        user.orderNo = out_trade_no
                        user.isOpenVipFaild = true
                        successOpenVip(user)
                    }
                }
            }, {
                hideLoading()
                if (retryCount > 0) {
                    retryCount--
                    topBar.postDelayed({ openVip(out_trade_no) }, 1000)
                } else {
                    hideLoading()
                    val user = UserManager.getInstance().curUser
                    user.isVip = 1
                    user.vipType = VipConfig.getVipValueByText(curVipType)
                    user.orderNo = out_trade_no
                    user.isOpenVipFaild = true
                    successOpenVip(user)
                }
            })
    }

    private fun successOpenVip(user: User) {
        toast("会员开通成功")
        UserManager.getInstance().saveUser(user)
        AdConfig.isShowAd = false
        setResult(Activity.RESULT_OK)
        finish()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doUserEvent(event: UserEvent) {
        if (UserManager.getInstance().isVip) {
            toast("会员开通成功")
            AdConfig.isShowAd = false
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun doUserRefreshEvent(event: UserRefreshEvent) {
        hideLoading()
    }
}
